package com.atguigu.gulimall.seckill.controller;

import com.atguigu.common.utils.R;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Slf4j
@Controller //能接收页面跳转的Controller
//@RestController //不跳转页面的 controller
public class SeckillController {

    @Autowired
    SeckillService seckillService;

    /**
     * 返回当前时间可以参与的秒杀商品信息
     *
     * @return
     */
    @ResponseBody //返回json数据
    @GetMapping("/currentSeckillSkus")
    public R getCurrentSeckillSkus() {
        log.info("currentSeckillSkus正在执行.......");

        List<SeckillSkuRedisTo> vos = seckillService.getCurrentSeckillSkus();
        return R.ok().setData(vos);
    }

    /**
     * 查询sku参与的秒杀活动信息
     *
     * @param skuId
     * @return
     */
    @ResponseBody
    @GetMapping("/sku/seckill/{skuId}")
    public R getSkuSeckillInfo(@PathVariable("skuId") Long skuId) {

        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        SeckillSkuRedisTo to = seckillService.getSkuSeckillInfo(skuId);
//        System.out.println("要查询的skuId"+to.getSkuId());
        return R.ok().setData(to);
    }

    /**
     * 进行秒杀抢购
     *
     * @param killId
     * @param key
     * @param num
     * @return
     * @RequestParam : 请求参数，必须要带
     */
    @GetMapping("/kill")
    public String secKill(@RequestParam("killId") String killId,
                          @RequestParam("key") String key,
                          @RequestParam("num") Integer num,
                          Model model) {
        //1. 拦截器判断是否登录
        String orderSn = seckillService.kill(killId,key,num);

        model.addAttribute("orderSn",orderSn);
        return "success";
    }
}
